import express from 'express';
import { createServer } from 'http';
import { Server } from 'socket.io';

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: "*"
  }
});

const rooms = new Map();

io.on('connection', (socket) => {
  console.log('新玩家加入,玩家id:', socket.id);
  socket.on('createRoom', () => {
    // toString(36)将该小数转换为 36 进制字符串。36 进制表示法使用数字 0-9 和字母 a-z（共 36 个字符）表示数值。例如，0.123456789 可能转换为类似 "0.4a7b9c..." 的字符串
    const roomId = Math.random().toString(36).substring(2, 8);
    rooms.set(roomId, { players: [socket.id] });
    socket.join(roomId);
    socket.emit('roomCreated', { roomId, playerId: socket.id });
  });

  socket.on('joinRoom', (roomId) => {
    const room = rooms.get(roomId);
    if (!room) {
      socket.emit('error', 'Room not found');
      return;
    }
    if (room.players.length >= 2) {
      socket.emit('error', 'Room is full');
      return;
    }
    room.players.push(socket.id);
    socket.join(roomId);
    socket.emit('gameJoined', { roomId, playerId: socket.id });

    if (room.players.length === 2) {
      io.to(roomId).emit('gameStart', {
        // 黑白玩家绑定玩家id,默认创建房间的玩家是黑棋，加入者是白棋，黑棋先下
        black: room.players[0],
        white: room.players[1]
      });
    }
  });

  socket.on('move', ({ roomId, row, col }) => {
    const room = rooms.get(roomId);
    if (!room) return;
    const playerIndex = room.players.indexOf(socket.id);
    const isValidPlayer = playerIndex !== -1;
    if (isValidPlayer) {
      // 广播房间内玩家，当前是哪个玩家下了这一步棋
      io.to(roomId).emit('moveMade', { row, col, player: socket.id });
    }
  });

  socket.on('disconnect', () => {
    for (const [roomId, room] of rooms.entries()) {
      if (room.players.includes(socket.id)) {
        io.to(roomId).emit('playerLeft');
        rooms.delete(roomId);
      }
    }
  });
});

const port = process.env.PORT || 4399;
httpServer.listen(port, () => {
  console.log(`服务器正在端口${port}上运行`);
});